/**
 * date : 2010-11-10
 * comment : BoardController 
 * 
 *  게시판 관련 모든 컨트롤 담당
 * 			
 */
package wetogether.community.control;


import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import wetogether.community.service.BoardService;
import wetogether.community.util.CommonConstants;
import wetogether.community.util.FileUploadClass;
import wetogether.community.vo.AttachmentVO;
import wetogether.community.vo.BoardVO;
import wetogether.community.vo.CommentsVO;
import wetogether.community.vo.ContentListVO;
import wetogether.community.vo.ListVO;

public class BoardController extends MultiActionController {
	private Log log = LogFactory.getLog(getClass());
	private BoardService boardService;

	public void setBoardService(BoardService boardService) {
		this.boardService = boardService;
	}
	/**
	 * tiles 용
	 * 
	 */
	public ModelAndView tilesSetting(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		//request.setAttribute("locationId", request.getParameter("locationId"));
		mav.setViewName(request.getParameter("flag"));
		return mav;
	}
	
	/**
	 * Date : 2010-11-12
	 * Author : Jeon So-Eui
	 * Comment
	 * 		게시판 클릭시 getContentList() 
	 * 		-> 글 목록 보기
	 * 			검색 후 해당 검색어에 맞는 글 목록 보기
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getContentList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		ContentListVO cvo= new ContentListVO();
		bind(request, cvo);
		String pageParam = cvo.getPage();
		if(pageParam == null || pageParam == "") {
			pageParam = "1";
		}
		cvo.setPage(pageParam);
		cvo.setContentPerPage(CommonConstants.CONTENT_NUMBER_PER_PAGE);
		String findSetting = request.getParameter("findSetting");
		if(findSetting != null) {			
			if(findSetting.equals("contentName")) {
				cvo.setMemberId(request.getParameter("findName"));
			} else if(findSetting.equals("contentTitle")) {
				cvo.setTitle(request.getParameter("findName"));
			}
		}
		ListVO lvo = boardService.getContentList(cvo);
		//mav.setViewName("list");
		//mav.setViewName("community/response/list");
		mav.addObject("lvo", lvo);
		mav.addObject("boardId", cvo.getBoardId());
		mav.addObject("locationId", cvo.getLocationId());
		return mav;
	}
	
	/**
	 * Date:	2010-11-12
	 * Author:	Shin In-soo
	 * Comments
	 * - write폼에서 받은 board, attachment데이터를 컨트롤
	 * - uploadFile을 받아 null이 아니면 파일 전송 null이면 boardVO만.
	 * - 파일 업로드 부분을 모듈화 할 여지가 있음
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView addContent(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("in addContent");		
		ModelAndView mv=new ModelAndView();		
		BoardVO bvo=new BoardVO();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		FileUploadClass fls=new FileUploadClass();
		String path=getServletContext().getRealPath("/")+"upload";		
		try {			
			bind(request, bvo);
			MultipartFile multipartFile= multipartRequest.getFile("uploadFile");
			if(!multipartFile.isEmpty()) {
				bvo.setAttachmentVO(fls.fileUpload(multipartFile, path));				
			}
			boardService.addContent(bvo);
			mv.addObject("boardVO", bvo);
			mv.addObject("getPage", request.getParameter("getPage"));
		} catch (Exception e) {
			mv.addObject("info", e.getMessage());
			e.printStackTrace();
		}
		mv.setViewName("show_content");
		return mv; 
	}
	
	/**
	 * Date:	2010-11-12
	 * Author:	Shin In-soo
	 * Comments
	 * 	- 답글메서드
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView addReply(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("in addReply");
		ModelAndView mav=new ModelAndView();
		BoardVO bvo=new BoardVO();
		String getPage=request.getParameter("getPage");	
		try {
			bind(request, bvo);
			System.out.println("bvo: "+bvo);
			boardService.addReply(bvo);
			mav.addObject("boardVO", bvo);
			mav.addObject("getPage",getPage);
		} catch (Exception e) {
			mav.addObject("info", e.getMessage());
			e.printStackTrace();
		}
		mav.setViewName("show_content");
		return mav; 
	}
	
	/**
	 * Date:	2010-11-12
	 * Author:	Shin In-soo
	 * Comments
	 * 	- boardVO받아와 show_content로 보내준다.
	 * 	- getPage : 답글시 부모글의 페이지로 가기위해 부모의 페이지를 넣어줌
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getContent(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("[Control]in getContent");
		ModelAndView mav=new ModelAndView();
		BoardVO bvo=new BoardVO();
		String getPage=request.getParameter("getPage");
		try {
			bind(request, bvo);
			System.out.println("[bvo] "+bvo);			
			mav.addObject("boardVO", boardService.getContent(bvo.getContentId()));
			mav.addObject("getPage",getPage);
			mav.addObject("locationId", bvo.getLocationId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		mav.setViewName("show_content");
		return mav;
	}
	
	/**
	 * Date:	2010-11-12
	 * Author:	Shin In-soo
	 * Comments
	 * 	- 글 삭제
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView deleteContent(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mav=new ModelAndView();
		BoardVO bvo=new BoardVO();
		try {
			System.out.println("####IN DELETE CONTENT####");
			bind(request, bvo);
			boardService.deleteContent(bvo.getContentId());
			mav.addObject("locationId", bvo.getLocationId());
			mav.addObject("boardId", bvo.getBoardId());
			mav.addObject("getPage", request.getParameter("getPage"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mav.setViewName("delete_result");
		return mav;
	}
	
	
	/** 
	 * date : 2010-11-11
	 * author : Kim Jong-sun
	 * comment : 댓글 관련 메서드
	 * 
	 * 댓글 쓰기
	 * 댓글 저장 후 해당 글의 commentsHits up
	 */
	public ModelAndView addComments(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// JSON 한글처리
		response.setContentType("application/x-json;  charset=UTF-8");
		// no 캐시
		response.setHeader("Cache-Control", "no-cache");
		ModelAndView mav = new ModelAndView();
		CommentsVO commentsVO = new CommentsVO();
		String viewName = "error";
		
		bind(request, commentsVO);	// form 으로부터 넘어온 데이터 commentsVO 복사 
		
		
		try {
			boardService.addComments(commentsVO);		// 댓글 추가 메서드 호출
			viewName = "addComments";					// 댓글 추가 성공시 viewName 설정
		} catch(SQLException sqlExp){
			log.warn(sqlExp.getMessage());
		} catch(Exception exp){
			log.warn(exp.getMessage());
		}
		
		// 저장된 댓글을 jsp에 보여주기 위해 JSON 으로 데이터 전송
		JSONObject jsonComments = JSONObject.fromObject(commentsVO);		// VO를 JSON에 담고
		mav.addObject("commentsResult", jsonComments);						// ModelAndView 에 세팅
		mav.setViewName(viewName);
		System.out.println("addComments : " + commentsVO.toString() + ", viewName : " + viewName);
		return mav;
	}
	/**
	 * 댓글 삭제 
	 * 해당 글의 댓글 삭제 후 commentsHits 도 down
	 */
	public ModelAndView deleteComments(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		String viewName = "error";
		
		// client 요청으로부터 넘어오는 parameter : contentId, commentsId
		int contentId = Integer.parseInt(request.getParameter("contentId"));
		int commentsId = Integer.parseInt(request.getParameter("commentsId"));

		try {
			boardService.deleteComments(contentId, commentsId);		// 댓글 삭제 메서드 호출
			viewName = "deleteComments";							// 댓글 삭제 성공시 viewName 설정
		} catch(SQLException sqlExp){
			log.warn(sqlExp.getMessage());
		} catch(Exception exp){
			log.warn(exp.getMessage());
		}
		
		mav.addObject("commentsId", commentsId);
		mav.setViewName(viewName);
		System.out.println("contentId : " + contentId + ", commentsId : " + commentsId + ", viewName : " + viewName);
		return mav;
	}

	/**
	 * 댓글 목록 가져오기
	 * 
	 * contentId에 해당하는 댓글목록 가져오기
	 */
	public ModelAndView getCommentsList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// JSON 한글처리
		response.setContentType("application/x-json;  charset=UTF-8");
		// no 캐시
		response.setHeader("Cache-Control", "no-cache");
		ModelAndView mav = new ModelAndView();
		String viewName = "getCommentsList";
		ArrayList<CommentsVO> commentsList = null;		// 댓글 저장을 위한 list
		// 게시물 번호
		String inputContentId = request.getParameter("contentId");
		
		int contentId = 0;
		// null 값이 입력될 경우 parseInt() 호출 시 java.lang.NumberFormatException 발생 때문에 
		// contentId 값이 있을 경우에만 댓글 목록 가져오기
		if(!inputContentId.equals("")){
			contentId = Integer.parseInt(inputContentId);	// 넘어오는 글번호
		}

		try {
			commentsList = boardService.getCommentsList(contentId);			// contentId 게시물의 댓글 목록을 가져온다
		} catch(SQLException sqlExp){
			log.warn(sqlExp.getMessage());
			viewName = "error";
		} catch(Exception exp){
			log.warn(exp.getMessage());
		}
		
		// 댓글 목록을 JSON 으로 전송
		JSONArray jsonCommentsList = JSONArray.fromObject(commentsList);
		mav.addObject("list", jsonCommentsList);
		mav.setViewName(viewName);
		System.out.println("getCommentsList : " + contentId + ", viewName : " + viewName);
		return mav;
	}
	/**
	 * Date:	2010-11-15
	 * Author:	Shin In-soo
	 * Comment:	콘텐츠 수정
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView modifyContent(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("in modifyContent");
		ModelAndView mav=new ModelAndView();
		BoardVO bvo=new BoardVO();
		try {
			bind(request, bvo);
			boardService.modifyContent(bvo);
			mav.addObject("boardVO", bvo);
			mav.addObject("getPage",request.getParameter("getPage"));
		} catch (Exception e) {
			mav.addObject("info", e.getMessage());
			e.printStackTrace();
		}
		mav.setViewName("show_content");
		return mav; 
	}
}
